package com.testcontact;

import java.util.Arrays;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.SectionIndexer;
import android.widget.TextView;

public class TestContactActivity extends Activity {
	/** Called when the activity is first created. */
	private String[] mNicks;
	private MyListView lvContact;
	private SideBar indexBar;
	private WindowManager mWindowManager;
	private TextView mDialogText;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		findView();

	}

	private void findView() {
		mNicks = getContact();
		lvContact = (MyListView) this.findViewById(R.id.lvContact);
		lvContact.setAdapter(new ContactAdapter(this));
		indexBar = (SideBar) findViewById(R.id.sideBar);
		lvContact.setmHeaderViewVisible(true);
		lvContact.setPinnedHeaderView(this, R.layout.title,
				R.id.contactitem_catalog);
		indexBar.setListView(lvContact);
		// 监听listview的滑动,根据listview滑动的位置,高亮显示sidebar当前位置.
		lvContact.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				String name = null;
				for (int i = 0; i < mNicks.length; i++) {
					if (i == firstVisibleItem) {
						name = mNicks[i];
					}
				}
				String l = converterToFirstSpell(name).substring(0, 1);
				char firstChar = l.toUpperCase().charAt(0);
				indexBar.setHighLight(firstChar);
				lvContact.refreshView(visibleItemCount);
			}

		});
		mDialogText = (TextView) LayoutInflater.from(this).inflate(
				R.layout.list_position, null);
		mDialogText.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
						| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);
		mWindowManager.addView(mDialogText, lp);
		indexBar.setTextView(mDialogText);
	}

	class ContactAdapter extends BaseAdapter implements SectionIndexer {
		private Context mContext;

		@SuppressWarnings("unchecked")
		public ContactAdapter(Context mContext) {
			this.mContext = mContext;
			// this.mNicks = nicks;
			// 排序(实现了中英文混排)
			Arrays.sort(mNicks, new PinyinComparator());
		}

		@Override
		public int getCount() {
			return mNicks.length;
		}

		@Override
		public Object getItem(int position) {
			return mNicks[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final String nickName = mNicks[position];
			ViewHolder viewHolder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.contact_item, null);
				viewHolder = new ViewHolder();
				viewHolder.tvCatalog = (TextView) convertView
						.findViewById(R.id.contactitem_catalog);
				viewHolder.ivAvatar = (ImageView) convertView
						.findViewById(R.id.contactitem_avatar_iv);
				viewHolder.tvNick = (TextView) convertView
						.findViewById(R.id.contactitem_nick);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			// 先获取首字母
			String catalog = converterToFirstSpell(nickName).substring(0, 1)
					.toUpperCase();
			// 如果是第一行,肯定要显示目录.也就是ABC的标题

			if (position == 0) {
				viewHolder.tvCatalog.setVisibility(View.VISIBLE);
				viewHolder.tvCatalog.setText(catalog);
				viewHolder.tvCatalog.setTag(catalog);
			} else {
				// 然后判断上一个的首字母
				String lastCatalog = converterToFirstSpell(mNicks[position - 1])
						.substring(0, 1);
				// 上一个的首字母是不是和这个一样,如果一样的话,不显示标题了.不一样的话,说明是新的目录了.whatever.

				if (catalog.equalsIgnoreCase(lastCatalog)) {
					viewHolder.tvCatalog.setVisibility(View.GONE);
					viewHolder.tvCatalog.setTag(catalog);
				} else {
					viewHolder.tvCatalog.setVisibility(View.VISIBLE);
					viewHolder.tvCatalog.setText(catalog);
					viewHolder.tvCatalog.setTag(catalog);
				}
			}

			viewHolder.ivAvatar.setImageResource(R.drawable.default_avatar);
			viewHolder.tvNick.setText(nickName);
			return convertView;
		}

		class ViewHolder {
			TextView tvCatalog;// 目录
			ImageView ivAvatar;// 头像
			TextView tvNick;// 昵称
		}

		/**
		 * 回调函数.sidebar通过调用这个方法比较list view中的联系人的字母是否和sidebar中点击的字母一致.
		 * 如果一致则返回该字母listview中的位置,否则返回-1.
		 */
		@Override
		public int getPositionForSection(int section) {
			for (int i = 0; i < mNicks.length; i++) {
				String l = converterToFirstSpell(mNicks[i]).substring(0, 1);
				char firstChar = l.toUpperCase().charAt(0);
				if (firstChar == section) {
					return i;
				}
			}
			return -1;
		}

		@Override
		public int getSectionForPosition(int position) {
			return 0;
		}

		@Override
		public Object[] getSections() {
			return null;
		}
	}

	/**
	 * 昵称
	 */
	// private static String[] nicks =
	// {"阿雅","北风","张山","李四","欧阳锋","郭靖","黄蓉","杨过","凤姐","芙蓉姐姐","发改委","范玮琪","疯狂烤翅","移联网","樱木花道","风清扬","张三丰","梅超风"};
	/**
	 * 获取手机联系人
	 * 
	 * @return
	 */
	private String[] getContact() {
		Cursor cur = getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI,
				null,
				null,
				null,
				ContactsContract.Contacts.DISPLAY_NAME
						+ " COLLATE LOCALIZED ASC");
		String[] nicks = new String[cur.getCount()];
		while (cur.moveToNext()) {
			int displayNameColumn = cur
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
			String disPlayName = cur.getString(displayNameColumn);
			nicks[cur.getPosition()] = disPlayName;
		}
		return nicks;

	}

	/**
	 * 汉字转换位汉语拼音首字母，英文字符不变
	 * 
	 * @param chines
	 *            汉字
	 * @return 拼音
	 */
	public static String converterToFirstSpell(String chines) {
		String pinyinName = "";
		char[] nameChar = chines.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (int i = 0; i < nameChar.length; i++) {
			if (nameChar[i] > 128) {// 如果大于128则是中文.
				try { // 将char转换成拼音首拼大写字母
					pinyinName += PinyinHelper.toHanyuPinyinStringArray(
							nameChar[i], defaultFormat)[0].charAt(0);
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			} else {// 英文字母
				pinyinName += nameChar[i];
			}
		}
		return pinyinName;
	}
}